package com.mb.user.service;

import com.mb.common.pojo.User;
import com.mb.common.utils.MD5Util;
import com.mb.common.utils.MapperUtil;
import com.mb.user.mapper.UserMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {
    @Autowired(required = false)
    private UserMapper userMapper;

    public boolean checkUsername(String username) {
        int exit = userMapper.selectCountByUsername(username);
        return exit==0;
    }

    public void doRegist(User user) {
        //缺少userId
        String userId = UUID.randomUUID().toString();
        user.setUserId(userId);
        //对密码进行加密
        user.setUserPassword(MD5Util.md5(user.getUserPassword()));
        userMapper.insertUser(user);
    }
    @Autowired
    private StringRedisTemplate redisTemplate;

    /*
    *
    * */
    public String doLogin(User user) {
        ValueOperations<String,String> opsForString = redisTemplate.opsForValue();
        user.setUserPassword(MD5Util.md5(user.getUserPassword()));
        User exit = userMapper.selectUsernameAndPassword(user);
        if(exit == null){
            return "";
        }else {
            //生成与用户有关的key值
            String loginkey="login_"+user.getUserName();
            if(redisTemplate.hasKey(loginkey)){
                //说明曾经有人登陆过这个账号
                String lastTicket = opsForString.get(loginkey);
                redisTemplate.delete(lastTicket);
            }

            //key
            String ticket="EM_TICKET"
                    +System.currentTimeMillis()
                    +user.getUserName();
            //value
            exit.setUserPassword(null);
            exit.setUserName(exit.getUserNickname());
            //将exit转换成json
            try{
                String userJson = MapperUtil.MP.writeValueAsString(exit);
                opsForString.set(ticket,userJson,2, TimeUnit.HOURS);
                opsForString.set(loginkey,ticket,2,TimeUnit.HOURS);
                return ticket;
            }catch (Exception e){
                e.printStackTrace();
                return "";
            }
        }
    }

    public String queryUserJson(String ticket) {
        ValueOperations<String, String> opsForString
                = redisTemplate.opsForValue();
        Long leftTime =
                redisTemplate.getExpire(ticket,TimeUnit.MILLISECONDS);
        //保证 某些情况 login超时时间和ticket一致
        String loginKey="login_"+obtainUsername(ticket);
        //-2 表示过期了  剩余超时时间大于0
        if(leftTime<1000*60*60){
            Boolean expire = redisTemplate.expire(ticket,2,TimeUnit.HOURS);
            if(expire){
                redisTemplate.expire(loginKey,2,TimeUnit.HOURS);
            }
        }
        return opsForString.get(ticket);
    }

    public String obtainUsername(String ticket){
        return ticket.substring(23);
    }

    public void deleteTicket(String ticket) {
        if(StringUtils.isNotEmpty(ticket)){
            redisTemplate.delete(ticket);
            String username=obtainUsername(ticket);
            String loginKey="login_"+username;
            redisTemplate.delete(loginKey);
        }
    }

}
